package com.ad.aidai.fragments.create_order;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ad.aidai.R;
import com.ad.aidai.common.ADFragmentManager;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.listener.OnActivityBackPressedListener;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.common.widgets.colorpop.ColorPopPageFragment;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.events.CommonEvent;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideTopExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.flyco.dialog.widget.NormalListDialog;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.mingle.entity.MenuEntity;
import com.mingle.sweetpick.DimEffect;
import com.mingle.sweetpick.RecyclerViewDelegate;
import com.mingle.sweetpick.SweetSheet;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 填写订单
 * <p>
 * Created by Yusxon on 16/12/17.
 */

public class CreateOrderFragment extends ColorPopPageFragment implements CreateOrderContract.View,
        OnActivityBackPressedListener {

    View fragment_view;
    @BindView(R.id.tv_order_type)
    TextView tvOrderType;
    @BindView(R.id.tv_num_of_order_content_text)
    TextView tvNumOfOrderContentText;
    @BindView(R.id.tv_num_of_address_delivery_text)
    TextView tvNumOfAddressDeliveryText;
    @BindView(R.id.tv_push_address)
    TextView tvPushAddress;
    @BindView(R.id.tv_push_time)
    TextView tvPushTime;
    @BindView(R.id.tv_order_end_time)
    TextView tvOrderEndTime;
    @BindView(R.id.et_order_content)
    EditText etOrderContent;
    @BindView(R.id.et_address_delivery)
    EditText etAddressDelivery;
    @BindView(R.id.et_reward_money)
    EditText etRewardMoney;
    @BindView(R.id.rl_create_order_view)
    RelativeLayout rlCreateOrderView;

    private CreateOrderContract.Presenter mPresenter;

    private SweetSheet pushPlaceSweetSheet;
    private SweetSheet pushTimeSweetSheet;

    private NormalDialog dialog;
    private BaseAnimatorSet mBasIn;
    private BaseAnimatorSet mBasOut;

    private LoadingDialog loadingDialog;

    @Override
    public View onCreateFragmentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        fragment_view = inflater.inflate(R.layout.fragment_create_order,
                container, false);
        ButterKnife.bind(this, fragment_view);
        new CreateOrderPresenter(getContext(), this).subscribe();

        fragment_view.setClickable(true);

        mBasIn = new BounceTopEnter();
        mBasOut = new SlideTopExit();

        initListener();

        pushPlaceSweetSheet = new SweetSheet(rlCreateOrderView);
        //设置数据源 (数据源支持设置 list 数组,也支持从菜单中获取)
        pushPlaceSweetSheet.setMenuList(mPresenter.getPushPlaceMenuEntity());
        //根据设置不同的 Delegate 来显示不同的风格.
        pushPlaceSweetSheet.setDelegate(new RecyclerViewDelegate(true));
        //根据设置不同Effect 来显示背景效果BlurEffect:模糊效果.DimEffect 变暗效果
        pushPlaceSweetSheet.setBackgroundEffect(new DimEffect(6));
        //设置点击事件
        pushPlaceSweetSheet.setOnMenuItemClickListener(new SweetSheet.OnMenuItemClickListener() {
            @Override
            public boolean onItemClick(int position, MenuEntity menuEntity1) {
                mPresenter.selectPushPlace(position);
                return true;
            }
        });

        pushTimeSweetSheet = new SweetSheet(rlCreateOrderView);
        //设置数据源 (数据源支持设置 list 数组,也支持从菜单中获取)
        pushTimeSweetSheet.setMenuList(mPresenter.getPushTimeMenuEntity());
        //根据设置不同的 Delegate 来显示不同的风格.
        pushTimeSweetSheet.setDelegate(new RecyclerViewDelegate(true));
        //根据设置不同Effect 来显示背景效果BlurEffect:模糊效果.DimEffect 变暗效果
        pushTimeSweetSheet.setBackgroundEffect(new DimEffect(6));
        //设置点击事件
        pushTimeSweetSheet.setOnMenuItemClickListener(new SweetSheet.OnMenuItemClickListener() {
            @Override
            public boolean onItemClick(int position, MenuEntity menuEntity1) {
                mPresenter.selectPushTime(position);
                return true;
            }
        });

        return fragment_view;
    }

    @Override
    public boolean haveHeader() {
        return true;
    }

    @Override
    public View getHeaderView(View fragment_view) {
        return fragment_view.findViewById(R.id.fl_top);
    }

    @Override
    public void onBackgroundAnimationEnd() {
        Context context = getContext();
        if (context != null) {
            Animation fade_in = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in);
            fragment_view.startAnimation(fade_in);
            fragment_view.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @OnClick({R.id.iv_back, R.id.tv_submit, R.id.ll_order_type, R.id.ll_push_address, R.id
            .ll_push_time, R.id.ll_order_end_time})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                if (checkEdit()) {
                    getFragmentManager().popBackStack();
                    if (etOrderContent.isFocused()) {
                        closeSoftInput(etOrderContent);
                    } else if (etAddressDelivery.isFocused()) {
                        closeSoftInput(etAddressDelivery);
                    } else if (etRewardMoney.isFocused()) {
                        closeSoftInput(etRewardMoney);
                    }
                } else {
                    showBackDialog();
                }
                break;
            case R.id.tv_submit:
                mPresenter.submit();
                break;
            case R.id.ll_order_type:
                chooseOrderType();
                break;
            case R.id.ll_push_address:
                mPresenter.openPushAddress();
                break;
            case R.id.ll_push_time:
                pushTimeSweetSheet.toggle();
                break;
            case R.id.ll_order_end_time:
                settingEndTime();
                break;
        }
    }

    @Override
    public void openPushAddress() {
        pushPlaceSweetSheet.toggle();
    }

    private void initListener() {
        etOrderContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                tvNumOfOrderContentText.setText(charSequence.length() + "");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        etAddressDelivery.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvNumOfAddressDeliveryText.setText(s.length() + "");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void setPresenter(CreateOrderContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void toast(String message) {
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showOrderType(String type) {
        tvOrderType.setText(type);
        tvOrderType.setTextColor(Color.BLACK);
    }

    @Override
    public String getOrderContent() {
        return etOrderContent.getText().toString();
    }

    @Override
    public String getOrderAddressOfDelivery() {
        return etAddressDelivery.getText().toString();
    }

    @Override
    public String getEndTime() {
        return tvOrderEndTime.getText().toString();
    }

    @Override
    public String getRewardMoney() {
        return etRewardMoney.getText().toString();
    }

    /**
     * 选择订单类型
     */
    private void chooseOrderType() {
        final NormalListDialog dialog = new NormalListDialog(getContext(), mPresenter.getTypeMenuItem());
        dialog.title("请选择")
                .titleTextSize_SP(18)
                .titleBgColor(ContextCompat.getColor(getContext(), R.color.colorTheme))
                .itemPressColor(Color.parseColor("#85D3EF"))
                .itemTextColor(Color.parseColor("#303030"))
                .itemTextSize(14)
                .cornerRadius(0)
                .widthScale(0.8f)
                .setItemExtraPadding(6, 6, 6, 6)
                .show(R.style.myDialogAnim);

        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                mPresenter.chooseTypeMenuItem(position);
                dialog.dismiss();
            }
        });
    }

    private boolean clickEndTime = false;

    /**
     * 设置截止时间
     */
    private void settingEndTime() {
        if(clickEndTime) {
            clickEndTime = false;
            return ;
        }
        clickEndTime = true;
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        new TimePickerDialog.Builder()
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String text = getDateToString(millseconds);
                        tvOrderEndTime.setText(text);
                        tvOrderEndTime.setTextColor(Color.BLACK);
                    }
                })
                .setCancelStringId("取消")
                .setSureStringId("设置")
                .setTitleStringId("截止时间选择")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
                .setHourText("时")
                .setMinuteText("分")
                .setCyclic(false)
                .setMinMillseconds(System.currentTimeMillis())
                .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                .setCurrentMillseconds(System.currentTimeMillis() + 9000 * 60)
                .setThemeColor(ContextCompat.getColor(getContext(), R.color.colorTheme))
                .setType(Type.ALL)
                .setWheelItemTextNormalColor(ContextCompat.getColor(getContext(), R.color
                        .timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(ContextCompat.getColor(getContext(), R.color
                        .timepicker_toolbar_bg))
                .setWheelItemTextSize(14)
                .build()
                .show(getFragmentManager(), "all");
    }

    private String getDateToString(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d = new Date(time);
        return sf.format(d);
    }

    @Override
    public void showPushPlace(String placeName) {
        tvPushAddress.setText(placeName);
        tvPushAddress.setTextColor(Color.BLACK);
    }

    @Override
    public void showPushTime(String pushTime) {
        tvPushTime.setText(pushTime);
        tvPushTime.setTextColor(Color.BLACK);
    }

    /**
     * 检查是否有编辑过
     *
     * @return
     */
    public boolean checkEdit() {
        boolean edit = CheckUtil.checkStrNull(tvOrderType.getText().toString())
                && CheckUtil.checkStrNull(etOrderContent.getText().toString())
                && CheckUtil.checkStrNull(etAddressDelivery.getText().toString())
                && CheckUtil.checkStrNull(tvPushAddress.getText().toString())
                && CheckUtil.checkStrNull(tvPushTime.getText().toString())
                && CheckUtil.checkStrNull(tvOrderEndTime.getText().toString())
                && CheckUtil.checkStrNull(etRewardMoney.getText().toString());

        return edit;
    }

    @Override
    public boolean onActivityBackPressed() {
        if (pushPlaceSweetSheet.isShow() || pushTimeSweetSheet.isShow()) {
            if (pushPlaceSweetSheet.isShow()) {
                pushPlaceSweetSheet.dismiss();
            }
            if (pushTimeSweetSheet.isShow()) {
                pushTimeSweetSheet.dismiss();
            }
        } else {
            if (checkEdit()) {
                RxBus.getInstance().postEvent(new CommonEvent(CommonEvent.IS_EXIT_CREATE_ORDER));
                getFragmentManager().popBackStack();
                return false;
            }
            showBackDialog();
        }
        return false;
    }

    /**
     * 显示返回的弹出框
     */
    private void showBackDialog() {
        if (dialog == null) {
            dialog = new NormalDialog(getContext());
            dialog.content("爱代单未提交，确认离开？")
                    .style(NormalDialog.STYLE_TWO)
                    .titleTextSize(20)
                    .btnText("确定", "取消")
                    .showAnim(mBasIn)
                    .dismissAnim(mBasOut);
        }
        if (!dialog.isShowing()) {
            dialog.show();
        }
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        exit();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                });
    }

    /**
     * 关闭软键盘
     *
     * @param view 对应的EditText
     */
    public void closeSoftInput(View view) {
        InputMethodManager inputManager = (InputMethodManager) getActivity().getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    private void exit() {
        getFragmentManager().popBackStack();
        RxBus.getInstance().postEvent(new CommonEvent(CommonEvent.IS_EXIT_CREATE_ORDER));
    }

    @Override
    public void sendSuccess() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (loadingDialog != null && loadingDialog.isShowing()) {

                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //登录成功,进入主页
                        exit();
                    }
                });
            }
        }).start();
    }

    @Override
    public void showLoading() {
        //显示加载对话框
        loadingDialog = new LoadingDialog(getActivity());
        loadingDialog.setLoadingText("努力发送中...")
                .setFailedText("发送失败")
                .setSuccessText("订单已发出")
                .show();
    }

    @Override
    public void showLoadingWithoutAnim() {
        loadingDialog = new LoadingDialog(getActivity());
        loadingDialog.setLoadingText("加载中...")
                .setFailedText("加载失败")
                .setSuccessText("加载完成")
                .closeFailedAnim()
                .closeSuccessAnim()
                .setShowTime(200)
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    @Override
    public void onStart() {
        ADFragmentManager.addListener(this);
        ADFragmentManager.addTag(this.getClass().getSimpleName());
        super.onStart();
    }

    @Override
    public void onDestroy() {
        ADFragmentManager.removeListener();
        ADFragmentManager.removeTag();
        super.onDestroy();
    }
}
